package com.jiedeng.controller;

import com.jiedeng.controller.index.BasicReportController;
import com.jiedeng.controller.index.HomepageController;
import com.jiedeng.dao.*;
import com.jiedeng.model.*;
import com.jiedeng.util.DatetimeUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 覃远龙
 * @ClassName: ProjectPersonController
 * @Description:
 * @date 2017/8/14 10:12
 */
@RestController
@Scope("prototype")
@RequestMapping("/project")
public class ProjectPersonController {
    private final Logger log = LoggerFactory.getLogger(ProjectPersonController.class);
    @Autowired
    IProjectRepository projectRepository;

    @Autowired
    IProjectPersonRepository projectPersonRepository;

    @Autowired
    ICorpRepository corpRepository;

    @Autowired
    IProjectCorpRepository projectCorpRepository;

    @Autowired
    ISysProjectGPSRepository sysProjectGPSRepository;

    @Autowired
    HomepageController homepageController;

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public List<Project> getAllProject() {
        return projectRepository.findAll();
    }

    @RequestMapping(value = "/by_person", method = RequestMethod.GET)
    public List<Project> getProjectByPerson(long personId) {

        List<ProjectPerson> projectPersonList = projectPersonRepository.findByPersonId(personId);
        List<Project> projects = new ArrayList<Project>();
        for (ProjectPerson p : projectPersonList) {
            if (p.getProjectId() > 0) {
                Project project = projectRepository.getOne(p.getProjectId());
                if (project != null) {
                    projects.add(project);
                }
            }
        }

        return projects;
    }

    @RequestMapping(value = "/by_corp", method = RequestMethod.GET)
    public List<Project> getProjectByCorp(long corpId) {
        List<ProjectCorp> projectCorps = projectCorpRepository.findByCorpId(corpId);
        List<Project> projects = new ArrayList<Project>();
        for (ProjectCorp p : projectCorps) {
            if (p.getProjectId() > 0) {
                Project project = projectRepository.getOne(p.getProjectId());
                if (project != null) {
                    projects.add(project);
                }
            }
        }

        return projects;
    }

    @RequestMapping(value = "/savepeople")
    @ApiOperation(value = "01003） 更新t_project_person表数据（数据上行）")
    public Rst saveProjectPerson(@RequestBody List<ProjectPerson> projectPeople) {
        List<ProjectPerson> updateArr = new ArrayList<>();
        List<ProjectPerson> saveArr = new ArrayList<>();
        List<ProjectPerson> delArr = new ArrayList<>();
        Map<Long, ProjectPerson> delMap = new HashMap<Long, ProjectPerson>();
        for (ProjectPerson p : projectPeople) {
            if (p.getId() > 0) {
                updateArr.add(projectPersonRepository.save(p));
            } else {
                List<ProjectPerson> projectPersonList = projectPersonRepository.findByProjectIdAndPostId(p.getProjectId(), p.getPostId());
                for (ProjectPerson projectPerson : projectPersonList) {
                    if (!delMap.containsKey(projectPerson.getId())) {
                        delMap.put(projectPerson.getId(), projectPerson);
                        delArr.add(projectPerson);
                    }
                }
                saveArr.add(projectPersonRepository.save(p));
            }
        }
        //projectID和postId
        for (ProjectPerson projectPerson : delArr) {
            projectPersonRepository.delete(projectPerson);
        }
        Rst rst = new Rst();
        rst.setResultCode(200);
        rst.setMsg("上传成功");
        Map<String, List<ProjectPerson>> map = new HashMap<>();
//        map.put("update", updateArr);
        map.put("newInsert", saveArr);
        map.put("delete", delArr);
        rst.setResult(map);

        return rst;
    }

    /**
     * 保存打点
     *
     * @param sysProjectGPSList
     * @return
     */
    @RequestMapping(value = "/saveProjectGps")
    @ApiOperation(value = "1402)上传打点数据（数据上行）")
    public Rst saveProjectGps(@RequestBody List<SysProjectGPS> sysProjectGPSList) {
        if (sysProjectGPSList != null && sysProjectGPSList.size() > 0) {
//            List<SysProjectGPS> gpsList = sysProjectGPSRepository.findByCaption(sysProjectGPSList.get(0).getCaption());
//            List<SysProjectGPS> addSysProjectGPSList = new ArrayList<>(10);
//            String caption = sysProjectGPSList.get(0).getCaption();
//            if (gpsList != null && gpsList.size() > 0) {
//                caption += DatetimeUtil.getDateyyyyMMddNone();
//            }
            for (SysProjectGPS sysProjectGPS : sysProjectGPSList) {
//                sysProjectGPS.setCaption(caption);
                sysProjectGPSRepository.save(sysProjectGPS);
//                if (sysProjectGPS.getGroupNum() != null && sysProjectGPS.getId() != null) {
//                } else {
//                    sysProjectGPSRepository.save(sysProjectGPS);
//                }
//                addSysProjectGPSList.add(sysProjectGPS);
            }
           /* for (SysProjectGPS sysProjectGPS : addSysProjectGPSList) {
                sysProjectGPSRepository.save(sysProjectGPS);
            }*/
        }
        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("上传成功");

        return rst;
    }

    /**
     * 获取maxGroupNum
     *
     * @return
     */
    @RequestMapping(value = "/getMaxGroupNum")
    public Long getMaxGroupNum() {
        Long groupNum = sysProjectGPSRepository.selectMaxGroupNum();
        if (groupNum != null) {
            return groupNum;
        }
        return 0l;
    }

    /**
     * 删除打点
     *
     * @param projectGpsIds
     * @return
     */
    @RequestMapping(value = "/deleteProjectGps")
    @ApiOperation(value = "1403）删除打点数据")
    public Rst deleteProjectGps(String projectGpsIds) {
        if (!StringUtils.isEmpty(projectGpsIds)) {
            String[] projectGpsIdArray = projectGpsIds.split(",");
            for (String id : projectGpsIdArray) {
                sysProjectGPSRepository.deleteById(id);
            }
        }
        Rst rst = new Rst();
        rst.setResultCode(0);
        rst.setMsg("上传成功");
        rst.setResult(projectGpsIds);
        return rst;
    }

    /**
     * 项目打点
     *
     * @param personId
     * @param projectGpsIds
     * @return
     */
    @RequestMapping(value = "/projectPointOut")
    @ApiOperation(value = "1401）返回相关工程打点数据（数据下行）")
    public Rst projectPointOut(String personId, String projectGpsIds) {
        log.info(projectGpsIds);
        if (StringUtils.isEmpty(personId)) {
            Rst rst = new Rst();
            rst.setResultCode(200);
            rst.setMsg("上传失败，personId不能为空");
            return rst;
        }
        Map<String, String> pGpsIdsMap = new HashMap<String, String>(16);
        String[] gpsIds = null;
        if (!StringUtils.isEmpty(projectGpsIds)) {
            gpsIds = projectGpsIds.split(",");
            for (String gpsId : gpsIds) {
                pGpsIdsMap.put(gpsId, gpsId);
            }
        }
        // Person person=personRepository.getOne(Long.valueOf(personId));
        List<SysProjectGPS> sysProjectGPSList = sysProjectGPSRepository.findSysProjectGPSByPerson(Long.valueOf(personId));
        List<SysProjectGPS> newInsert = new ArrayList<>(10);
        Map<String, SysProjectGPS> sysProjectGPSMap = new HashMap<>(16);
        for (SysProjectGPS sysProjectGPS : sysProjectGPSList) {
            sysProjectGPSMap.put(sysProjectGPS.getId(), sysProjectGPS);
            if (!pGpsIdsMap.containsKey(sysProjectGPS.getId())) {
                newInsert.add(sysProjectGPS);
            }
        }
        String deleteGpsIds = "";
        if (gpsIds != null) {
            for (String gpsId : gpsIds) {
                if (!sysProjectGPSMap.containsKey(gpsId)) {
                    if (deleteGpsIds != "") {
                        deleteGpsIds += ",";
                    }
                    deleteGpsIds += gpsId;
                }
            }
        }
        Rst rst = new Rst();
        rst.setResultCode(200);
        rst.setMsg("上传成功");
        Map<String, Object> map = new HashMap<>(2);
        map.put("newInsert", newInsert);
        map.put("delete", deleteGpsIds);
        rst.setResult(map);
        return rst;
    }

    /**
     * 项目新增或修改
     * t_project表的删除和添加
     *
     * @param personId
     * @param projectIds
     * @return
     */
    @RequestMapping(value = "/projectAddAndDelete")
    public Rst projectAddAndDelete(String personId, String projectIds) {
        if (StringUtils.isEmpty(personId)) {
            Rst rst = new Rst();
            rst.setResultCode(200);
            rst.setMsg("上传失败，personId不能为空");
            return rst;
        }
        Map<Long, String> pIdsMap = new HashMap<Long, String>(16);
        String[] pIds = null;
        if (!StringUtils.isEmpty(projectIds)) {
            pIds = projectIds.split(",");
            for (String pId : pIds) {
                pIdsMap.put(Long.valueOf(pId), pId);
            }
        }
        // Person person=personRepository.getOne(Long.valueOf(personId));
        String corpIds = homepageController.findAllPersonCorp(Long.valueOf(personId));
        List<Long> corpIdList = new ArrayList<>(10);
        if (!StringUtils.isEmpty(corpIds)) {
            String[] corpIdArry = corpIds.split(",");
            for (String s : corpIdArry) {
                corpIdList.add(Long.valueOf(s));
            }
        }
        List<Project> projectList = projectRepository.findProjectByCorpIdsSQL(corpIdList);

        List<Project> newInsert = new ArrayList<>(10);
        Map<Long, Project> projectMap = new HashMap<>(16);
        for (Project project : projectList) {
            projectMap.put(project.getId(), project);
            if (!pIdsMap.containsKey(project.getId())) {
                newInsert.add(project);
            }
        }
        String deleteGpsIds = "";
        if (pIds != null) {
            for (String id : pIds) {
                if (!projectMap.containsKey(Long.valueOf(id))) {
                    if (deleteGpsIds != "") {
                        deleteGpsIds += ",";
                    }
                    deleteGpsIds += id;
                }
            }
        }

        Rst rst = new Rst();
        rst.setResultCode(200);
        rst.setMsg("上传成功");
        Map<String, Object> map = new HashMap<>(2);
        map.put("newInsert", newInsert);
        map.put("delete", deleteGpsIds);
        rst.setResult(map);
        return rst;
    }
}
